import 'dart:developer';

import 'package:im_base/private/app_ext.dart';
import 'package:im_base/public/ext/im_base_controller.dart';
import 'package:im_base/public/global/im_keys.dart';
import 'package:im_base/public/service/tim_service.dart';
import 'package:im_base/public/tim/components/conversation/classify_conversation/end_widget/logic.dart';
import 'package:im_base/public/tim/components/conversation/classify_conversation/going_on_widget/logic.dart';
import 'package:tencent_im_sdk_plugin/manager/v2_tim_manager.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_conversation.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info.dart';

import '../state.dart';

class ClassifyConversationLogic extends IMBaseController {
  late V2TIMManager _v2timManager;
  final state = ConversationState();

  @override
  void onInit() {
    _v2timManager = TimService.instance.v2timManager!;
    super.onInit();
  }

  @override
  void onReady() {
    _watchConversation();
    _watchDelete();
    _watchFriendChange();
    super.onReady();
    getConversation();
  }

  @override
  void onClose() {
    super.onClose();
  }

  @override
  void refresh() {
    state.nextSeq = '0';
    super.refresh();
  }

  ///加载更多,获取最后一条消息的标识
  void loadMore() {
    if (state.hasMore) {
      getConversation();
    }
  }

  ///拉取历史会话列表
  void getConversation() async {
    final conversation = await _v2timManager
        .getConversationManager()
        .getConversationList(nextSeq: state.nextSeq, count: state.pageSize);
    if (conversation.code == 0) {
      if (state.nextSeq == '0') {
        try {
          if (conversation.data!.conversationList == null ||
              conversation.data!.conversationList!.isEmpty) {
          } else {
            conversation.data!.conversationList!.removeWhere((element) {
              return element!.userID == "admin" || element.lastMessage == null;
            });
            state.conversationList.addAll(conversation.data!.conversationList!);
          }
        } catch (e) {}
      } else {
        conversation.data!.conversationList!.removeWhere((element) {
          return element!.userID == "admin" || element.lastMessage == null;
        });
        state.conversationList.addAll(conversation.data!.conversationList!);
      }
      if (state.conversationList.length > 50) {
        state.nextSeq = state
            .conversationList[state.conversationList.length - 1]!
            .lastMessage!
            .seq!;
      }

      state.hasMore = state.nextSeq != '0';
    }
    setConversationData();
  }

  ///监听会话列表变动
  void _watchConversation() {
    addKeyListener(IMKeys.conversationList, (conversation) {
      updateConversation(conversation);
    });

    addKeyListener(IMKeys.newConversation, (conversation) {
      state.conversationList.addAll(conversation);
      setConversationData();
    });
  }

  ///如果当前没有会话,或者是新会话不在会话列表中,则直接添加
  ///如果已在当前会话列表中,则比对会话id,更新该会话
  void updateConversation(List<V2TimConversation> list) async {
    if (state.conversationList.isEmpty) {
      state.conversationList.addAll(list);
    } else {
      list.forEach((element) {
        log('-------${element.isPinned}--${element.unreadCount}');
        final conID = element.conversationID;
        state.conversationList.removeWhere((e) => e!.conversationID == conID);
        state.conversationList.add(element);
      });
    }
    setConversationData();
  }

  ///根据会话id删除会话
  void deleteConversation(String conID) async {
    await _v2timManager
        .getConversationManager()
        .deleteConversation(conversationID: conID)
        .then((value) {
      if (value.code == 0) {
        state.conversationList
            .removeWhere((element) => element!.conversationID == conID);
        setConversationData();
      } else {
        showToast('删除失败:[${value.code}]:${value.desc}');
      }
    });
  }

  void _watchDelete() {
    addKeyListener(IMKeys.deleteConversation, (p0) {
      var con =
          state.conversationList.where((element) => element?.groupID == p0);
      if (con.isNotEmpty) {
        deleteConversation(con.first!.conversationID);
      }
    });
  }

  void _watchFriendChange() {
    addKeyListener(IMKeys.friendInfoChange, (value) {
      if (value is List<V2TimFriendInfo>) {
        value.forEach((info) {
          state.conversationList
              .where((element) => element?.userID == info.userID)
              .first
              ?.showName = info.friendRemark ?? '';
        });
        setConversationData();
      }
    });
  }

  ///使用是否置顶标识进行中或已结束,如果是已置顶则为进行中,否则为已结束
  void setConversationData() {
    findLogic<GoingOnWidgetLogic>()
        .updateList(state.conversationList.where((element) {
      return !(element?.isPinned ?? false);
    }).toList());
    findLogic<EndInquiryLogic>()
        .updateList(state.conversationList.where((element) {
      return (element?.isPinned ?? true);
    }).toList());
  }
}
